package com.chcit.mobile.mvp.common.presenter;

import android.app.Application;

import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.common.SPDErrorHandle;
import com.elvishew.xlog.XLog;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.chcit.mobile.mvp.common.contract.ServerContract;
import com.jess.arms.utils.RxLifecycleUtils;


@FragmentScope
public class ServerPresenter extends BasePresenter<ServerContract.Model, ServerContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ServerPresenter(ServerContract.Model model, ServerContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void testAndSave(String address) {
        final String url ;
        if(!address.endsWith("/")){
            url =address+"/";
        }else{
            url = address;
        }
        mModel.test(url+"#url_ignore")
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new SPDErrorHandle<String> (mErrorHandler){
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRootView.showLoading();
                    }

                    @Override
                    public void onNext(String s) {

                        RetrofitUrlManager.getInstance().setGlobalDomain(url);
                        SharedPreUtils.getInstance().putString(ConfigKeys.API_HOST.name(), url);
                        mRootView.toLoginPage();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
